import Ext from "@/common/web_extension";

const showBadge = (options: Record<string, any>) => {
    const { clear, text, color, blink } = {
        clear: false,
        text: '',
        color: '#ff0000',
        blink: 0,
        ...(options || {}),
    };

    if (clear) {
        return Ext.action.setBadgeText({ text: '' });
    }

    Ext.action.setBadgeBackgroundColor({ color });
    Ext.action.setBadgeText({ text });

    if (blink) {
        setTimeout(() => {
            Ext.action.getBadgeText({}).then((curText: any) => {
                if (curText !== text) return false;
                return Ext.action.setBadgeText({ text: '' });
            });
        }, blink);
    }

    return true;
};


const toggleRecordingBadge = (isRecording: string, options: Record<string, any>) => {
    return showBadge({
        color: '#ff0000',
        text: 'R',
        ...(options || {}),
        clear: !isRecording,
    });
};

const toggleInspectingBadge = (isInspecting: string, options: Record<string, any>) => {
    return showBadge({
        color: '#ffa800',
        text: 'S',
        ...(options || {}),
        clear: !isInspecting,
    });
};

const togglePlayingBadge = (isPlaying: string, options: Record<string, any>) => {
    return showBadge({
        color: '#14c756',
        text: 'P',
        ...(options || {}),
        clear: !isPlaying,
    });
};


export const panelUpdateBadge = (args: any) => {
    const dict: any = {
        play: togglePlayingBadge,
        record: toggleRecordingBadge,
        inspect: toggleInspectingBadge,
    };
    const fn = dict[args.type];

    if (!fn) {
        throw new Error(`E221: unknown type for updating badge, '${args.type}'`);
    }

    return fn(!args.clear, args);
}